package com.itheima52.mobilesafe.activity;

import java.util.ArrayList;
import java.util.List;

import com.itheima52.mobilesafe.R;
import com.itheima52.mobilesafe.bean.AppInfo;
import com.itheima52.mobilesafe.engine.AppInfos;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.view.annotation.ViewInject;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ActionBar.LayoutParams;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.text.format.Formatter;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.ScaleAnimation;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;

public class AppManagerActivity extends Activity implements OnClickListener {

	@ViewInject(R.id.list_view)
	private ListView listView;
	@ViewInject(R.id.tv_rom)
	private TextView tv_rom;
	@ViewInject(R.id.tv_sd)
	private TextView tv_sd;
	private List<AppInfo> appInfos;
	private List<AppInfo> userAppInfos;
	private List<AppInfo> systemAppInfos;
	@ViewInject(R.id.tv_app)
	private TextView tv_app;
	private PopupWindow popupWindow;
	private AppInfo clickAppInfo;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		initUI();
		initData();

	}

	private class AppManagerAdapter extends BaseAdapter {

		@Override
		public int getCount() {
			return 1 + userAppInfos.size() + 1 + systemAppInfos.size();
		}

		@Override
		public Object getItem(int position) {
			if (position == 0) {
				return null;
			} else if (position == userAppInfos.size() + 1) {
				return null;
			}
			AppInfo appInfo;

			if (position < userAppInfos.size() + 1) {
				// 把多出来的特殊的条目减掉
				appInfo = userAppInfos.get(position - 1);

			} else {

				int location = userAppInfos.size() + 2;

				appInfo = systemAppInfos.get(position - location);
			}

			return appInfo;
		}

		@Override
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return position;
		}

		@SuppressLint("NewApi")
		@Override
		public View getView(int position, View convertView, ViewGroup parent) {

			// 如果当前的position等于0 表示应用程序
			if (position == 0) {
				TextView textView = new TextView(AppManagerActivity.this);
				textView.setText("用户程序(" + userAppInfos.size() + ")");
				textView.setTextColor(Color.WHITE);
				textView.setBackgroundColor(Color.GRAY);
				return textView;

			} else if (position == userAppInfos.size() + 1) {
				TextView textView = new TextView(AppManagerActivity.this);
				textView.setText("系统程序(" + systemAppInfos.size() + ")");
				textView.setTextColor(Color.WHITE);
				textView.setBackgroundColor(Color.GRAY);
				return textView;
			}

			AppInfo appInfo;
			if (position < userAppInfos.size() + 1) {
				// 把多出来的特殊条目减掉
				appInfo = userAppInfos.get(position - 1);
			} else {
				int location = userAppInfos.size() + 2;

				appInfo = systemAppInfos.get(position - location);
			}

			View view = null;
			ViewHolder holder;
			if (convertView != null && convertView instanceof LinearLayout) {// 复用为空,说明第一次进来
				view = convertView;
				holder = (ViewHolder) convertView.getTag();
			} else {

				view = View.inflate(AppManagerActivity.this,
						R.layout.item_app_manager, null);
				holder = new ViewHolder();
				holder.iv_icon = (ImageView) view.findViewById(R.id.iv_icon);
				holder.tv_apk_size = (TextView) view
						.findViewById(R.id.tv_apk_size);
				holder.tv_location = (TextView) view
						.findViewById(R.id.tv_location);
				holder.tv_name = (TextView) view.findViewById(R.id.tv_name);
				view.setTag(holder);
			}

			holder.iv_icon.setBackground(appInfo.getIcon());
			holder.tv_apk_size.setText(Formatter.formatFileSize(
					AppManagerActivity.this, appInfo.getApkSize()));
			if (appInfo.isRom()) {
				holder.tv_location.setText("手机内存");
			} else {
				holder.tv_location.setText("sd卡");
			}
			holder.tv_name.setText(appInfo.getApkName());

			return view;
		}
	}

	static class ViewHolder {
		ImageView iv_icon;
		TextView tv_apk_size;
		TextView tv_location;
		TextView tv_name;
	}

	private Handler handler = new Handler() {

		public void handleMessage(android.os.Message msg) {
			AppManagerAdapter adapter = new AppManagerAdapter();
			listView.setAdapter(adapter);
		};
	};

	private void initData() {
		new Thread() {

			public void run() {

				appInfos = AppInfos.getAppInfos(AppManagerActivity.this);
				Log.e("应用所有的数量:", appInfos.size() + "");
				userAppInfos = new ArrayList<AppInfo>();
				systemAppInfos = new ArrayList<AppInfo>();

				for (AppInfo appInfo : appInfos) {
					if (appInfo.isUserApp()) {
						userAppInfos.add(appInfo);
					} else {
						systemAppInfos.add(appInfo);
					}
				}

				handler.sendEmptyMessage(0);

			};
		}.start();

	}

	private void initUI() {
		setContentView(R.layout.activity_app_manager);
		ViewUtils.inject(AppManagerActivity.this);
		// 获取到rom内存的运行剩余空间
		long rom_freeSpace = Environment.getDataDirectory().getFreeSpace();
		// 获取sd卡的剩余空间
		long sd_freeSpace = Environment.getExternalStorageDirectory()
				.getFreeSpace();
		tv_rom.setText("内存可用:"
				+ Formatter.formatFileSize(AppManagerActivity.this,
						rom_freeSpace));
		tv_sd.setText("sd卡可用:"
				+ Formatter.formatFileSize(AppManagerActivity.this,
						sd_freeSpace));

		UninstallReceiver receiver = new UninstallReceiver();
		IntentFilter filter = new IntentFilter(Intent.ACTION_PACKAGE_REMOVED);
		filter.addDataScheme("package");
		registerReceiver(receiver, filter);

		// 设置listview的滚动监听
		listView.setOnScrollListener(new OnScrollListener() {

			@Override
			public void onScrollStateChanged(AbsListView view, int scrollState) {
				// TODO Auto-generated method stub

			}

			@Override
			public void onScroll(AbsListView view, int firstVisibleItem,
					int visibleItemCount, int totalItemCount) {
				popupWindowDismiss();
				if (userAppInfos != null && systemAppInfos != null) {
					if (firstVisibleItem > (userAppInfos.size() + 1)) {
						// 系统应用程序
						tv_app.setText("系统程序(" + systemAppInfos.size() + ")");
					} else {
						// 用户应用程序
						tv_app.setText("应用程序(" + userAppInfos.size() + ")");
					}
				}

			}
		});
		listView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				// 获取到当前点击的item对象
				Object obj = listView.getItemAtPosition(position);
				if (obj != null && obj instanceof AppInfo) {
					clickAppInfo = (AppInfo) obj;
					View contentView = view.inflate(AppManagerActivity.this,
							R.layout.item_popup, null);
					LinearLayout ll_uninstall = (LinearLayout) contentView
							.findViewById(R.id.ll_uninstall);
					LinearLayout ll_run = (LinearLayout) contentView
							.findViewById(R.id.ll_run);
					LinearLayout ll_share = (LinearLayout) contentView
							.findViewById(R.id.ll_share);
					LinearLayout ll_detail = (LinearLayout) contentView
							.findViewById(R.id.ll_detail);
					ll_uninstall.setOnClickListener(AppManagerActivity.this);
					ll_run.setOnClickListener(AppManagerActivity.this);
					ll_share.setOnClickListener(AppManagerActivity.this);
					ll_detail.setOnClickListener(AppManagerActivity.this);

					popupWindowDismiss();
					popupWindow = new PopupWindow(contentView, -2, -2);
					// 需要注意:使用popupwindows使用动画必须设置背景
					popupWindow.setBackgroundDrawable(new ColorDrawable(
							Color.TRANSPARENT));
					int[] location = new int[2];
					view.getLocationInWindow(location);
					popupWindow.showAtLocation(parent, Gravity.LEFT
							+ Gravity.TOP, 70, location[1]);

					ScaleAnimation scaleAnimation = new ScaleAnimation(0.5f,
							1.0f, 0.5f, 1.0f, Animation.RELATIVE_TO_SELF, 0.5f,
							Animation.RELATIVE_TO_SELF, 0.5f);
					scaleAnimation.setDuration(300);

					contentView.startAnimation(scaleAnimation);

				}

			}
		});

	}

	private class UninstallReceiver extends BroadcastReceiver {

		@Override
		public void onReceive(Context context, Intent intent) {
			System.out.println("有程序卸载了.");

		}

	}

	public void popupWindowDismiss() {

		if (popupWindow != null && popupWindow.isShowing()) {
			popupWindow.dismiss();
			popupWindow = null;
		}
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		popupWindowDismiss();

	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		// 卸载
		case R.id.ll_uninstall:
			Intent uninstall_localIntent = new Intent("android.intent.action.DELETE", Uri.parse("package:" + clickAppInfo.getApkPackageName()));
            startActivity(uninstall_localIntent);
            popupWindowDismiss();
            break;
		// 运行
		case R.id.ll_run:
			Intent intent = this.getPackageManager().getLaunchIntentForPackage(
					clickAppInfo.getApkPackageName());
			this.startActivity(intent);
			popupWindowDismiss();
			break;
		// 分享
		case R.id.ll_share:
			Intent localIntent = new Intent("android.intent.action.SEND");
			localIntent.setType("text/plain");
			localIntent.putExtra("android.intent.extra.SUBJECT", "分享");
			localIntent.putExtra("android.intent.extra.TEXT", "HI.推荐一个软件给你"
					+ clickAppInfo.getApkName());
			this.startActivity(Intent.createChooser(localIntent, "分享"));
			this.popupWindowDismiss();

			break;
		// 详细信息
		case R.id.ll_detail:
			Intent detail_intent = new Intent();
			detail_intent.setAction("android.settings.APPLICATION_DETAILS_SETTINGS");
			detail_intent.addCategory(Intent.CATEGORY_DEFAULT);
			detail_intent.setData(Uri.parse("package:"+clickAppInfo.getApkPackageName()));
			
			startActivity(detail_intent);

			break;

		default:
			break;
		}
	}
}
